package com.tanhua.manage.msg;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 消费者   处理消息
 * @author mxk
 * @date 2021/3/29 11:05
 */
@Component
@RocketMQMessageListener(topic = "tanhua-log",
        consumerGroup = "tanhua-log-consumer")
@Slf4j
public class LogMsgConsumer implements RocketMQListener<String> {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    @Autowired
    private LogService logService;
    // 模拟手机型号
    private static final String[] mockDevices = {
            "华为荣耀P30", "华为荣耀P29", "华为荣耀P28", "华为荣耀P27", "华为荣耀P26", "华为荣耀P25"
    };
    // 模拟操作地点
    private static final String[] mockCities = {
            "北京", "上海", "广州", "深圳", "天津", "石家庄"
    };

    @Override
    public void onMessage(String msg) {
        try {
            JSONObject jsonObject = JSONUtil.parseObj(msg);
            Long userId = jsonObject.getLong("userId");
            String type = jsonObject.get("type").toString();
            Date date = Convert.toDate(jsonObject.get("date"), null);

            //非空校验
            if (!ObjectUtil.isAllNotEmpty(userId,type,date)){
                return;
            }
            //判断这条日志记录是否已经存在
            int count = logService.count(Wrappers.<Log>lambdaQuery()
                    .eq(Log::getUserId, userId)
                    .eq(Log::getType, type)
                    .eq(Log::getCreated, date));
            if (count>0){
                return;
            }

            //创建时间和操作时间相同  只是类型不同
            String logTime = DateUtil.formatDate(date);

            Log log=new Log();
            log.setUserId(userId);
            log.setLogTime(logTime);
            log.setType(type);
            //随机生成设备
            log.setEquipment(mockDevices[RandomUtil.randomInt(0,mockDevices.length-1)]);
            //随机生成城市
            log.setPlace(mockCities[RandomUtil.randomInt(0,mockCities.length-1)]);
            log.setCreated(date);
            //将消息存入到tb_log表中
            logService.save(log);
        } catch (Exception e) {
           log.error("消息处理失败!msg="+msg);
        }
    }
}
